package com.mlethe.library.socialtool.core;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.mlethe.library.socialtool.callback.Callback;
import com.mlethe.library.socialtool.callback.OauthActionListener;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.sina.weibo.sdk.common.UiError;
import com.sina.weibo.sdk.openapi.IWBAPI;
import com.sina.weibo.sdk.openapi.WBAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 微博登录
 *
 * @author Mlethe
 */
public class Weibo implements Oauth<IWBAPI> {

    private static final String BASE_URL = "https://api.weibo.com/2";

    /**
     * 应用对应的权限，第三方开发者一般不需要这么多，可直接设置成空即可。
     */
    private static final String SCOPE = "email,direct_messages_read,direct_messages_write,"
            + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
            + "follow_app_official_microblog," + "invitation_write";

    private AuthInfo mAuthInfo;

    private IWBAPI mWBAPI;

    private String activityClass = "";

    private SelfWbAuthListener listener;

    private OauthActionListener mOauthListener;

    /**
     * 是否获取用户信息
     */
    private boolean isGetUserInfo = false;

    /**
     * 初始化
     *
     * @param context
     * @param appKey      新浪微博 appKey
     * @param redirectUrl 当前应用的回调页，第三方应用可以使用自己的回调页
     *                    建议使用默认回调页：https://api.weibo.com/oauth2/default.html
     */
    public Weibo(Context context, String appKey, String redirectUrl) {
        /**
         * scope 应用对应的权限，第三方开发者一般不需要这么多，可直接设置成空即可。
         */
        if (redirectUrl != null && !"".equals(redirectUrl)) {
            redirectUrl = "https://api.weibo.com/oauth2/default.html";
        }
        mAuthInfo = new AuthInfo(context, appKey, redirectUrl, SCOPE);
        listener = new SelfWbAuthListener();
    }

    @Override
    public IWBAPI getApi() {
        return mWBAPI;
    }

    /**
     * 创建WBAPI
     *
     * @param activity
     */
    public void init(Activity activity) {
        if (mWBAPI == null) {
            mWBAPI = WBAPIFactory.createWBAPI(activity);
            mWBAPI.registerApp(activity, mAuthInfo);
            mWBAPI.setLoggerEnable(true);
            activityClass = activity.getClass().getName();
        } else {
            if (!activityClass.equals(activity.getClass().getName())) {
                unregister();
                activityClass = "";
                init(activity);
            }
        }
    }

    /**
     * 是否获取用户信息
     *
     * @param flag true 是 false 否
     */
    public Weibo setGetInfoEnable(boolean flag) {
        isGetUserInfo = flag;
        return this;
    }

    /**
     * 授权登录回调
     * 请在调用 oauth() 方法前调用
     *
     * @param listener listener
     * @return
     */
    public Weibo setOauthActionListener(OauthActionListener listener) {
        this.mOauthListener = listener;
        return this;
    }

    /**
     * SSO 授权, 仅客户端
     */
    public void oauth() {
        if (!isAppInstalled()) {
            if (mOauthListener != null) {
                mOauthListener.onNotInstalled(Platform.WEIBO);
                mOauthListener = null;
            }
            return;
        }
        if (getApi() != null) {
            getApi().authorize(listener);
        }
    }

    /**
     * SSO 授权登录回调
     * 重要：发起 SSO 登录的 Activity 必须重写 onActivityResult
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (getApi() != null) {
            getApi().authorizeCallback(requestCode, resultCode, data);
        }
    }

    /**
     * 判断是否安装
     *
     * @return
     */
    @Override
    public boolean isAppInstalled() {
        if (getApi() == null || !getApi().isWBAppInstalled()) {
            return false;
        }
        return true;
    }

    /**
     * 取消注册
     */
    @Override
    public void unregister() {
        mWBAPI = null;
    }

    /**
     * 释放内存
     */
    @Override
    public void release() {
        mAuthInfo = null;
        unregister();
        listener = null;
        isGetUserInfo = false;
        mOauthListener = null;
    }

    private class SelfWbAuthListener implements WbAuthListener {
        @Override
        public void onComplete(Oauth2AccessToken oauth2AccessToken) {
            if (oauth2AccessToken.isSessionValid()) {
                if (!isGetUserInfo) {
                    if (mOauthListener != null) {
                        try {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("access_token", oauth2AccessToken.getAccessToken());
                            jsonObject.put("uid", oauth2AccessToken.getUid());
                            mOauthListener.onComplete(Platform.WEIBO, jsonObject);
                        } catch (JSONException e) {
                            e.printStackTrace();
                            mOauthListener.onFail(Platform.WEIBO);
                        } finally {
                            mOauthListener = null;
                        }
                    }
                    return;
                }
                isGetUserInfo = false;
                new HttpsThread(BASE_URL + "/users/show.json?access_token=" + oauth2AccessToken.getAccessToken() + "&uid=" + oauth2AccessToken.getUid(), new Callback() {
                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        if (mOauthListener != null) {
                            mOauthListener.onComplete(Platform.WEIBO, jsonObject);
                            mOauthListener = null;
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        if (mOauthListener != null) {
                            mOauthListener.onFail(Platform.WEIBO);
                            mOauthListener = null;
                        }
                    }
                }).start();
            } else {
                if (mOauthListener != null) {
                    mOauthListener.onFail(Platform.WEIBO);
                    mOauthListener = null;
                }
            }
        }

        @Override
        public void onError(UiError uiError) {
            if (mOauthListener != null) {
                mOauthListener.onFail(Platform.WEIBO);
                mOauthListener = null;
            }
        }

        @Override
        public void onCancel() {
            if (mOauthListener != null) {
                mOauthListener.onCancel(Platform.WEIBO);
                mOauthListener = null;
            }
        }
    }
}
